﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
	[Header("移动速度")]
	public float moveSpeed;

	[Header("怪物最大血量")]
	public float maxBlood;
	public float blood;

	[Header("怪物终点")]
	public Transform endPath;

	[Header("怪物血量视图")]
	public EnemyBloodView bloodView;

	public Queue<float> hurts = new Queue<float>(); // 承受的子弹的伤害



	/// <summary>
	/// 怪物受到攻击时
	/// </summary>
	public void DecBlood(float hurt) {
		blood = Mathf.Max(0, blood - hurt);
		bloodView.SetBloodValue(blood);
		if (blood == 0) {
			EnemyController.Singleton.delNum++;
			EnemyController.Singleton.DeleteEnemy(GetComponent<Enemy>());
			GameController.Singleton.AddDieEnemyCount();   // 打死一个怪物后

			// if (GameController.Singleton.JudgeGameOver())
			// 	GameController.Singleton.EndGame();
		}
	}

	private int index = 1;
	private float distance = 0;
	private Vector3 beginPos;
	private void Start() {
		beginPos = PathController.Singleton.paths[0].position;
		blood = maxBlood;
		bloodView.maxBlood = maxBlood;
	}
	private void Update() {

		if (GameController.Singleton.JudgeGameOver()) {
			UIController.Singleton.ShowResultPnl();
			return;
		}

		if (hurts.Count > 0 && blood > 0) {
			DecBlood(hurts.Dequeue());
		}

		if (index < PathController.Singleton.paths.Count) {
			PathController paCon = PathController.Singleton;
			Vector3 target = paCon.paths[index].position;
			transform.LookAt(target);

			// 每一帧的偏移量
			Vector3 translation = Vector3.forward * moveSpeed * Time.deltaTime;
			transform.Translate(translation);   // 自身坐标

			distance += translation.magnitude;  // magnitude指向量的模

			if (distance >= Vector3.Distance(target, beginPos)) {
				distance = 0;
				index++;
				beginPos = transform.position;
			}
		} else if (index == PathController.Singleton.paths.Count) {    // 此时怪物到达终点
			index++;
			// EnemyController.Singleton.DeleteEnemy(GetComponent<Enemy>());
			GameController.Singleton.DelBlood();   // 血量降低
			hurts.Enqueue(maxBlood + 1);    // 怪物到达终点给他一个最大伤害值
		}
	}
}

